package com.wuliu.driver.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {


    /**
     * 当且仅当
     * @return
     */
    @Bean
    public RedisTemplate<String,Object> cd(RedisConnectionFactory connectionFactory){
        RedisTemplate<String,Object> xx = new RedisTemplate();
        xx.setConnectionFactory(connectionFactory);// 设置连接工厂

        // 修改key的序列化方式  String的序列化方式
        xx.setKeySerializer(new  StringRedisSerializer());

        Jackson2JsonRedisSerializer<Object> op =
                new Jackson2JsonRedisSerializer<>(Object.class);


        // jackson 专门用来进行序列化和反序列化
        ObjectMapper objectMapper = new ObjectMapper();


        // 没有写这句话之前 Jackson2JsonRedisSerializer只序列化 public修饰的方法 get  set
        // jason你在序列化Person对象时 要把私有的 公有的属性 方法 构造方法全部考虑进去
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 我们在序列化时要把这个对象他是何种类型给写进去
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);


        op.setObjectMapper(objectMapper);



        // 修改value 的序列化方式  json的序列化方式
        xx.setValueSerializer(op);

        return xx;
    }

    //读取redis地址
    @Value("${spring.redis.host}")
    private String host;
    //读取redis端口
    @Value("${spring.redis.port}")
    private String port;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        //拼接redis地址
        String redisUrl = "redis://" + host + ":" + port;
        //设置redis地址
        //useSingleServer表示单台redis
        config.useSingleServer().setAddress(redisUrl);
        return Redisson.create(config);
    }
}
